package com.sleepcamel.exporter

import java.io.File

import com.sleepcamel.exporter.mappingGenerator.DomainJavaClassToMapping;
import com.sleepcamel.exporter.model.JavaDBClass;
import com.sleepcamel.exporter.model.category.StringCategory
import com.sleepcamel.exporter.model.generator.JPACodeGenerator
import com.sleepcamel.exporter.model.generator.JavaModelGenerator
import com.sleepcamel.exporter.persister.XMLPersister
import com.sleepcamel.exporter.reader.DataBaseMetaDataReader
import com.sleepcamel.rest.domain.JavaClass;
import com.sleepcamel.rest.domain.Project;
import com.sleepcamel.rest.domain.ProjectPackage;
import com.sleepcamel.rest.domain.TreeNode;
import com.sleepcamel.rest.domain.util.RestConstants;
import com.sleepcamel.exporter.util.JdbcUtils

class DBExporter {

	JdbcUtils jdbcUtils
	DataBaseMetaDataReader reader = new DataBaseMetaDataReader()
	JavaModelGenerator modelGen = new JavaModelGenerator()
	JPACodeGenerator codeGen = new JPACodeGenerator()
	XMLPersister persister = new XMLPersister()
	File modelDirectory
	String projectName = RestConstants.EXAMPLE_PROJECT_NAME;
	String packageName = RestConstants.EXAMPLE_PACKAGE_NAME;
	
	public void generateModelFiles(){
		use(StringCategory) {
			reader.jdbcUtils = jdbcUtils
			reader.processDB()

			modelGen.tables = reader.tables
			modelGen.packageName = packageName
			modelGen.process()
			
			codeGen.classes = modelGen.classes
			codeGen.rootDir = modelDirectory
			codeGen.projectName = projectName
			codeGen.packageName = packageName
			codeGen.debug = true
			codeGen.writeClassFiles()
			
			persister.tables = reader.tables
			persister.classes = modelGen.classes
			persister.outputDir = modelDirectory
			persister.persist()
		}
	}
	
	public List<JavaClass> getGeneratedJavaClasses(){
		return modelGen.classes;
	}

	public Project generateRESTProject(){
		Project restProject = new Project();
		restProject.setBaseMapping("/rest");
		restProject.setName(projectName);
		
		String [] packages = packageName.split("\\.");
		TreeNode topPackage = restProject
		ProjectPackage childPackage;
		packages.each{projectPackage->
			 childPackage = new ProjectPackage(projectPackage)
			 topPackage.addChild(childPackage)
			 topPackage = childPackage
		}

		for (JavaDBClass bean in codeGen.classes) {
			DomainJavaClassToMapping domainJavaClassToMapping = new DomainJavaClassToMapping(bean);
			childPackage.addChild(domainJavaClassToMapping.getMapping());
		}
		return restProject;
	}
}
